<template>
  <el-dialog v-model="dialogVisible" style="height: 800px" width="600" center align-center :show-close="false">
    <template #title>
      <custom-title title="批量支付" />
    </template>
    <div v-loading="isLoading" style="min-height: 100%">
      <div class="info">
        采购付款单编号：
        <template v-for="(item, index) in slipCodes">
          <span :class="{ slipCodes: true, subStr: slipCodes.length - 1 != index }">{{ item }}</span>
        </template>
        <div class="card" v-if="isLoaded">
          <div>
            <div>
              <div>关联合作方</div>
              <div>{{ detailInfo.partner.partnerName }}</div>
            </div>
            <!--          <div v-if="!isBatch">-->
            <!--            <div>应付金额</div>-->
            <!--            <div>￥{{ detailInfo.partner.payableAmount }}</div>-->
            <!--          </div>-->
            <!--          <div v-if="!isBatch">-->
            <!--            <div>已付金额</div>-->
            <!--            <div>￥{{ detailInfo.partner.paidAmount }}</div>-->
            <!--          </div>-->
            <div>
              <div>本次应付金额</div>
              <div>￥{{ detailInfo.partner.currentDueAmount }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="pay-content" v-if="isLoaded">
        <el-checkbox-group v-model="payTypeList">
          <el-checkbox v-for="item in detailInfo.paymentMethodList" :key="item.id" :label="item.name" :value="item.id" />
        </el-checkbox-group>
        <!--        start 账户支付-->
        <el-form
          v-if="payTypeList.includes(1)"
          :model="accountForm"
          label-position="top"
          ref="accountFormRef"
          :rules="accountFormRules"
        >
          <div class="pay-title">账户支付</div>
          <account-payment
            v-model="accountForm"
            formLabelVal="payment"
            :paymentAccountList="detailInfo.paymentAccountList"
            :receivingAccountList="detailInfo.receivingAccountList"
          ></account-payment>
        </el-form>
        <!--        end 账户支付-->
        <!--        start 现金-->
        <el-form v-if="payTypeList.includes(2)" :model="cashForm" label-position="top" ref="cashFormRef" :rules="cashFormRules">
          <div class="pay-title">现金支付</div>
          <cash-payment v-model="cashForm" formLabelVal="payment"></cash-payment>
        </el-form>
        <!--        end 现金-->
        <!--        start 预支付:采购付款单里面只会出现预付款支付，不会出现预收款-->
        <el-form
          v-if="payTypeList.includes(5)"
          :model="advanceForm"
          label-position="top"
          ref="advanceFormRef"
          :rules="advanceFormRules"
        >
          <div class="pay-title">预付款支付</div>
          <advance-repay-payment v-model="advanceForm" formLabelVal="payment"></advance-repay-payment>
        </el-form>
        <el-form
          v-if="payTypeList.includes(5)"
          :rules="advanceMoneyRules"
          :model="advanceForm.deductionRecordList"
          ref="moneyRef"
          inline-message
        >
          <advance-repay-table
            v-model:tableDataParam="advancesTableData"
            v-model:formDataParam="advanceForm"
            formLabelVal="payment"
            :tableHeadParam="advanceHead"
          ></advance-repay-table>
        </el-form>
        <!--        end 预支付-->
        <!--        start 借款单-->
        <el-form
          v-if="payTypeList.includes(4)"
          :model="repayForm"
          label-position="top"
          ref="repayFormRef"
          :rules="repayFormRules"
        >
          <div class="pay-title">借款还款单</div>
          <advance-repay-payment v-model="repayForm" formLabelVal="payment"></advance-repay-payment>
        </el-form>
        <el-form
          v-if="payTypeList.includes(4)"
          :rules="repayMoneyRules"
          :model="repayForm.deductionRecordList"
          ref="moneyRef"
          inline-message
        >
          <advance-repay-table
            v-model:tableDataParam="repayTableData"
            v-model:formDataParam="repayForm"
            :tableHeadParam="repayHead"
            formLabelVal="payment"
          ></advance-repay-table>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="payConfirm" :disabled="!payTypeList.length || isLoading"> 确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { accountFormInit, cashFormInit, formRulesInit, advanceRepayFormInit } from "@/utils/config";
import AccountPayment from "@/components/PayType/AccountPayment.vue";
import AdvanceRepayTable from "@/components/PayType/AdvanceRepayTable.vue";
import AdvanceRepayPayment from "@/components/PayType/AdvanceRepayPayment.vue";
import CashPayment from "@/components/PayType/CashPayment.vue";
import { ref, getCurrentInstance, computed, onMounted } from "vue";
import { batchPayments, paymentsDetail } from "@/apis/invoices";
import { ElMessage } from "element-plus";
import { accAdd } from "@/utils";
import { cloneDeep } from "lodash";

const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  selectSlipCodes: {
    type: Array,
    default: []
  },
  partnerAccountId: {
    type: String,
    default: ""
  }
});
const dialogVisible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});

const slipCodes = props.selectSlipCodes;
const currentPartnerAccount = props.partnerAccountId;
const emit = defineEmits(["update:modelValue", "handleSavePay"]);

const payTypeList = ref([]);
const moneyRef = ref(null);

//账户支付
const accountForm = ref(cloneDeep(accountFormInit));
const accountFormRef = ref(null);
const accountFormRules = formRulesInit;

//现金
const cashFormRef = ref(null);
const cashForm = ref(cloneDeep(cashFormInit));
const cashFormRules = formRulesInit;

//预付款
const advanceHead = ["单号", "未使用金额", "本单使用"];
const advanceMoneyRules = ref({});
const advancesTableData = ref([]);
const advanceFormRef = ref(null);
const advanceForm = ref(cloneDeep(advanceRepayFormInit));
const advanceFormRules = formRulesInit;

//借款单
const repayHead = ["借款还款单号", "应还金额", "本单还款"];
const repayFormRef = ref(null);
const repayForm = ref(cloneDeep(advanceRepayFormInit));
const repayFormRules = formRulesInit;
const repayMoneyRules = ref({});
const repayTableData = ref([]);

const detailInfo = ref({});
const isLoaded = ref(false);
const isLoading = ref(false);
const getPaymentsDetail = async () => {
  try {
    const { data } = await paymentsDetail({ slipCodes: slipCodes });
    isLoading.value = true;
    detailInfo.value = data ?? {};
    advancesTableData.value = data.advancePaymentList ?? [];
    repayTableData.value = data.repaymentStatementList ?? [];
    advancesTableData.value.length && addMoneyRule(advancesTableData, advanceMoneyRules, "advanceRule");
    repayTableData.value.length && addMoneyRule(repayTableData, repayMoneyRules, "repayRule");
    isLoaded.value = true;
    isLoading.value = false;
  } catch (err) {}
};

const currentRuleType = ref("");
const addMoneyRule = (tableData, tableRules, type) => {
  currentRuleType.value = type;
  tableData.value.forEach(v => {
    tableRules.value[v.slipCode] = [
      { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入正确的金额", trigger: "blur" },
      { validator: tableMoneyRule, trigger: "blur" }
    ];
  });
};
const tableMoneyRule = (rule, value, callback) => {
  let advanceMax = Number(advancesTableData.value.filter(v => v.slipCode == rule.field)[0]?.availableAmount);
  let repayMax = Number(repayTableData.value.filter(v => v.slipCode == rule.field)[0]?.availableAmount);
  if (value > repayMax) {
    callback(new Error("不能大于应还金额"));
  } else if (value > advanceMax) {
    callback(new Error("不能大于未使用金额"));
  } else {
    callback();
  }
};

/**
 * 确认支付
 */
const isPass = ref(false);
const payConfirm = async () => {
  //账户
  if (payTypeList.value.includes(1)) {
    isPass.value = await accountFormRef.value.validate();
  }
  //现金
  if (payTypeList.value.includes(2)) {
    isPass.value = await cashFormRef.value.validate();
  }
  //预付款
  if (payTypeList.value.includes(5)) {
    isPass.value = await advanceFormRef.value.validate();
    if (!isPass.value) return;
    if (!advancesTableData.value.length) return ElMessage.error("没有使用的单据");
    const advanceTotal = advancesTableData.value.reduce((accumulator, currentValue) => {
      return accAdd(accumulator, Number(currentValue.currentDeductionAmount));
    }, 0); // 初始值为0
    if (advanceTotal != Number(advanceForm.value.deductionAmount)) {
      isPass.value = false;
      return ElMessage.error("预付款未使用金额之和需等于付款金额");
    }
  }
  //还款单
  if (payTypeList.value.includes(4)) {
    isPass.value = await repayFormRef.value.validate();
    if (!isPass.value) return;
    if (!repayTableData.value.length) return ElMessage.error("没有使用的单据");
    const repayTotal = repayTableData.value.reduce((accumulator, currentValue) => {
      return accAdd(accumulator, Number(currentValue.currentDeductionAmount));
    }, 0); // 初始值为0
    if (repayTotal != Number(repayForm.value.deductionAmount)) {
      isPass.value = false;
      return ElMessage.error("借款还款单未使用金额之和需等于付款金额");
    }
  }
  if (!isPass.value) {
    return;
  }
  const totalMoneyArr = [
    accountForm.value.totalAmount,
    cashForm.value.totalAmount,
    advanceForm.value.deductionAmount,
    repayForm.value.deductionAmount
  ];
  const totalMoney = totalMoneyArr.reduce((accumulator, currentValue) => {
    return accAdd(accumulator, Number(currentValue));
  }, 0); // 初始值为0
  if (totalMoney != Number(detailInfo.value.partner.currentDueAmount)) {
    return ElMessage.error("本次应付金额和本次付款金额必须相等，请确认后操作");
  }
  savePaymentInfo();
};
const savePaymentInfo = async () => {
  if (payTypeList.value.includes(5)) {
    advanceForm.value.deductionRecordList = advancesTableData.value;
  }
  if (payTypeList.value.includes(4)) {
    repayForm.value.deductionAmount = repayTableData.value;
  }
  let data = {
    slipCodes,
    paymentMethodIds: payTypeList.value,
    accountPayment: payTypeList.value.includes(1) ? accountForm.value : null,
    cashPayment: payTypeList.value.includes(2) ? cashForm.value : null,
    advancePayment: payTypeList.value.includes(5) ? advanceForm.value : null,
    advanceReceipt: null, //预还款
    repaymentStatement: payTypeList.value.includes(4) ? repayForm.value : null
  };
  isLoading.value = true;
  try {
    await batchPayments(data);
    isLoading.value = false;
    dialogVisible.value = false;
    proxy.$modal.msgSuccess("操作成功");
    emit("handleSavePay");
  } catch (err) {
    isLoading.value = false;
  }
};

onMounted(() => {
  accountForm.value.receivingAccountId = currentPartnerAccount;
  getPaymentsDetail();
});
</script>

<style scoped lang="scss">
@import "../../comon";
</style>
